import axios from "axios";
import { encrypt, decrypt } from "./aes";

const instance = axios.create({
    baseURL: '/api',
    timeout: 5000,
    headers: {
        "Content-Type": "application/text/plain",
    },
    transformRequest: [function (data, headers) {
        if (data) {
            data = encrypt(data);
        }
        return data;
    }],
    transformResponse: [function (data) {
        return decrypt(data);
    }],
});

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    return config;
}, function (error) {
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    console.log(response);
    if (response.status == 200) {
        if (typeof response.data != 'object') {
            response.data = JSON.parse(response.data);
        }
        if (response.data.code != 200) {
            throw new Error(response.data.msg);
        }
    }
    return response.data.data;
}, function (error) {
    return Promise.reject(error);
});

export default instance;